package com.yangzb.java.sample.xmly;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.ArrayList;
import java.util.List;

public class UrlDecoder {
    private static final String script = FileUtil.readString("/Users/yzb/Desktop/source-code/sample/java-sample/src/main/resources/crypto-js.js", "utf-8");
    private static final ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
    private static final ScriptEngine engine= scriptEngineManager.getEngineByName("javascript");
    static {
        try {
            engine.eval(script);
        } catch (ScriptException e) {
            throw new RuntimeException(e);
        }
    }


    public static void main(String[] args) throws ScriptException {
        List<String> urls = new ArrayList<>();
        urls.add("pX7rCko1ZPLJXbyU3qjcDqAp042BK5yCrhhNlUZEBd6lHKILemhbvHD1YkhQ7FDbPYgHmgIwtklYyxmDgAysy5XcClqGB3yKYjZ8lBLZqWwiDKzGvtTEV0fGgrhjCCGIB22jecZDda6nI-6o5bRohQvc9qnrm1QHYyYHtwuLplq9geuuQf6Jbu9jzQT-s0m4uaeG529bY5WSqIXsvJbQmTU1cmkNzajf9tWRB101_7kJ8oJMqOEbS-WXOAE5GwNNWbOsyLGtgLDKA2cVNGGumTF7zH1_hUP3HsoHUBNv6VWll6ONmmENhkbMT7d1l9Bb");
        urls.add("pX7rCko1ZPLJXbyU3qjcDqAp042BK5yCrhhNlUZEBd6lHKILemhbvHD1YkhQ7FDbwq67wJuhimK2NNqC4HXrrfWnq95717dmiWlR5RqHKjzoMGyWcsu27hNGZeN2qVfcgFrKhMlSx_3vPs37ANBS7Qog9-mNq5S2tK6rIUYhtFsXkuFhCMYgVsbksSjcIbTKuaeG529bY5WSqIXsvJbQmTU1cmkNzajf9tWRB101_7kJ8oJMqOEbS-WXOAE5GwNNWbOsyLGtgLDKA2cVNGGumf4mQLianB8JgCB2RIZtD52ll6ONmmENhkbMT7d1l9Bb");
        for (String url : urls) {
            engine.eval(StrUtil.format(SCRIPT,url));
            Object test = engine.get("test");
            System.out.println(test);
        }
    }

    public static String decryptUrl(String url) throws ScriptException {
        engine.eval(StrUtil.format(SCRIPT,url));
        return Convert.toStr(engine.get("test"));
    }

    public static final String SCRIPT= ";function decryptUrl(ciphertext) {\n" +
            "    return CryptoJS.AES.decrypt(\n" +
            "        { ciphertext: CryptoJS.enc.Base64url.parse(ciphertext) },\n" +
            "        CryptoJS.enc.Hex.parse('aaad3e4fd540b0f79dca95606e72bf93'),\n" +
            "        {\n" +
            "            mode: CryptoJS.mode.ECB,\n" +
            "            padding: CryptoJS.pad.Pkcs7,\n" +
            "        }\n" +
            "    ).toString(CryptoJS.enc.Utf8);\n" +
            "}" +
            "var test =decryptUrl('{}')\n";
}
